package com.alinesno.cloud.common.web.base.exceptions;
import javax.servlet.http.HttpServletRequest;

import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.common.web.base.form.FormRepeatException;
import com.alinesno.cloud.common.web.base.response.ResponseBean;
import com.alinesno.cloud.common.web.base.response.ResponseGenerator;

/**
 * springboot全局异常处理
 * @author LuoAnDong
 * @since 2019年2月8日 下午2:24:05
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	/**
	 * 默认全局拦截
	 * @param req
	 * @param e
	 * @return
	 * @throws Exception
	 */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseBean defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
       
		log.error("前端调用异常", e);
    	
        String message = e.getMessage();
		String eclass = e.getClass().getName();
		
		log.debug("eclass:{} , message:{}" , eclass , message);
		
		String errorMsg = null;
		
		if (e instanceof FormRepeatException) {
			
			errorMsg = e.getMessage();
			
		} else if (message != null && message.startsWith(ServiceException.class.getName())) {
			
			errorMsg = message.substring(message.indexOf(":") + 1, message.indexOf("\n") - 1);
			
		} else if(eclass != null && message.startsWith("com.netflix.client.ClientException")) {
			
			errorMsg = "远程服务连接不可用,请确认服务是否启动:"+message ;
				
		} else if(eclass != null && eclass.startsWith("feign.FeignException")) {
			
			errorMsg = "远程服务连接异常,请联系服务管理员处理:"+message ; 
			
		}else {
			errorMsg = StringUtils.isEmpty(e.getMessage()) ? "系统异常！" : e.getMessage();
		}
		
        return ResponseGenerator.genFailMessage(errorMsg) ; 
    }
}